package cn.axj.crypt.secret.implement;

import cn.axj.crypt.constant.AlgorithmConstant;
import cn.axj.crypt.secret.BaseAlgorithmHttpInputMessage;
import cn.axj.crypt.secret.config.DesKeyConfg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.crypto.*;
import javax.crypto.spec.DESKeySpec;
import java.security.SecureRandom;

/**
 * @author aoxiaojun
 * @date 2020/12/15 15:41
 **/
@Component
public class DesAlgorithmHttpInputMessage extends BaseAlgorithmHttpInputMessage {

    /**
     * 算法密匙
     */

    private static String key;
    @Resource
    private DesKeyConfg desKeyConfg;


    @Autowired
    public void setKey() {
        DesAlgorithmHttpInputMessage.key = desKeyConfg.getKey();
    }

    /**
     * 数据加密，算法（DES）
     *
     * @param data
     *            要进行加密的数据
     * @return 加密后的数据
     */
    private String encryptBasedDes(String data) {
        String encryptedData;
        try {
            // DES算法要求有一个可信任的随机数源
            SecureRandom sr = new SecureRandom();
            DESKeySpec deskey = new DESKeySpec(key.getBytes());
            // 创建一个密匙工厂，然后用它把DESKeySpec转换成一个SecretKey对象
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
            SecretKey key = keyFactory.generateSecret(deskey);
            // 加密对象
            Cipher cipher = Cipher.getInstance("DES");
            cipher.init(Cipher.ENCRYPT_MODE, key, sr);
            // 加密，并把字节数组编码成字符串
            encryptedData = new sun.misc.BASE64Encoder().encode(cipher.doFinal(data.getBytes()));
        } catch (Exception e) {
            throw new RuntimeException("加密错误，错误信息：", e);
        }
        return encryptedData;
    }

    /**
     * 解密
     * @param cryptData
     * @return
     */
    private String decryptBasedDes(String cryptData) {
        String decryptedData;
        try {
            // DES算法要求有一个可信任的随机数源
            SecureRandom sr = new SecureRandom();
            DESKeySpec deskey = new DESKeySpec(key.getBytes());
            // 创建一个密匙工厂，然后用它把DESKeySpec转换成一个SecretKey对象
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
            SecretKey key = keyFactory.generateSecret(deskey);
            // 解密对象
            Cipher cipher = Cipher.getInstance("DES");
            cipher.init(Cipher.DECRYPT_MODE, key, sr);
            // 把字符串解码为字节数组，并解密
            decryptedData = new String(cipher.doFinal(new sun.misc.BASE64Decoder().decodeBuffer(cryptData)));
        } catch (Exception e) {
            throw new RuntimeException("解密错误，错误信息：", e);
        }
        return decryptedData;
    }


    @Override
    public String getBinding() {
        return AlgorithmConstant.DES;
    }

    @Override
    public String decrypt(String content) {
        return this.decryptBasedDes(content);
    }

    @Override
    public String encrypt(String content) {
        return this.encryptBasedDes(content);
    }
}
